package Fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import Entities.LoginReturnData;
import  Test.Test;
import Preferences.Preferences;
import com.example.zelonghu.testgps.NavigationHost;
import com.example.zelonghu.testgps.R;

import java.util.List;

/**
 * @author zelonghu QQ:1032006226
 * @name testGPS2
 * @class name：Fragment
 * @class describe
 * @time 2019/5/28 4:05 PM
 * @change
 * @chang time
 * @class describe
 */
public class LoginFragment extends Fragment implements View.OnClickListener {
    Button nologinbutton;
    Button submitbutton;
    Button cancelButton;
    EditText usernameET;
    EditText passwordET;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.testgps2_fragment_login,container,false);
        nologinbutton = (Button)view.findViewById(R.id.not_login);
        nologinbutton.setOnClickListener(this);
        submitbutton = (Button)view.findViewById(R.id.login_commit);
        submitbutton.setOnClickListener(this);
        cancelButton = (Button)view.findViewById(R.id.login_cancel);
        cancelButton.setOnClickListener(this);
        usernameET = (EditText)view.findViewById(R.id.user_id_editview);
        passwordET = (EditText)view.findViewById(R.id.user_pwd_editview);
        return view;
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.not_login:
                ((NavigationHost)getActivity()).navigateTo(new MainFragment(),false);
                break;
            case R.id.login_commit:
                //获取字符串
                String username = usernameET.getText().toString();
                String pwd = passwordET.getText().toString();
                //判断是否合法
                if(new Preferences(getContext()).isValid(username,pwd)){
                    //开启后台线程访问网络，前台等待。
                    new LoginThread(getContext()).start();
                    Toast.makeText(getContext(),"验证用户名密码正确性",Toast.LENGTH_LONG).show();
                }else{
                    //并不合法
                    Toast.makeText(getContext(),"请输入正确格式的用户名和密码",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.login_cancel:
                getFragmentManager().popBackStack();
                break;
        }
    }
    /*
    * @author 胡泽龙
    * @time 20190625
    * @todo 用户获得网络通信后得到的用户名和密码，
    *       具体方法是子线程调用handler.sendmessage来访问这里，然后决定下一步动作.
    *
    * */
    @SuppressLint("HandlerLeak")
    Handler loginhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //这是登录信息的返回信息
                    Bundle bundle = msg.getData();
                    Boolean isvalid = Boolean.parseBoolean( bundle.getString("isvalid"));
                    if(isvalid){
                        //身份合法
                        //写入身份
                        new Preferences(getContext()).save_login_info(bundle.getString("imagepath"),
                                bundle.getString("username"),bundle.getString("userdescribe"));
                        //跳转到下个页面
                        ( (NavigationHost)getActivity()).navigateTo(new MainFragment(),false);
                    }else{
                        //身份不合法

                        //TOast提示
                        Toast.makeText(getContext(),"您的身份不合法",Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };
    /**
     * @name LoginFragment
     * @class name：LoginFragment
     * @class describe
     * @author zelonghu
     * @time 2019/6/27 10:23 AM
     * @change
     * @chang time
     * @class 后台线程，需要和前台的一个handler做对应，所以将结果信息通过Message传到前台的handler进行处理
     */
    class LoginThread extends Thread {
        Context context;

        public LoginThread(Context context) {
            this.context = context;
        }

        @Override
        public void run() {
            try {
                //访问网络看是否登录成功

                try{//模拟耗时应用
                    Thread.sleep(2000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                //返回一个访问编码，通过编码进行以后的交流，同时返回用户的信息

                //这里使用TEST类模拟网络成功
                List<LoginReturnData> loginReturnDataList= Test.get_info_fromtest();
                LoginReturnData loginReturnData = loginReturnDataList.get(0);
                //将信息放入到Preferences中
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("isvalid",loginReturnData.getIsvalid());
                bundle.putString("loginstr",loginReturnData.getLoginstr());
                bundle.putString("imagepath",loginReturnData.getImagepath());
                bundle.putString("username",loginReturnData.getUsername());
                bundle.putString("userdescribe",loginReturnData.getUserdescribe());
                message.setData(bundle);
                message.what = 1;
                loginhandler.sendMessage(message);
                super.run();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

